package com.shitou.shitoumember.service.impl;

import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitoumember.entity.MemberEntity;
import com.shitou.shitoumember.entity.TokenEntity;
import com.shitou.shitoumember.service.MemberService;
import com.shitou.shitoumember.service.TokenService;
import com.shitou.shitoumember.vo.InterestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitoumember.dao.MemberInterestDao;
import com.shitou.shitoumember.entity.MemberInterestEntity;
import com.shitou.shitoumember.service.MemberInterestService;

import javax.annotation.Resource;

@SuppressWarnings("all")
@Transactional
@Service("memberInterestService")
public class MemberInterestServiceImpl extends ServiceImpl<MemberInterestDao, MemberInterestEntity> implements MemberInterestService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberInterestEntity> page = this.page(
                new Query<MemberInterestEntity>().getPage(params),
                new QueryWrapper<MemberInterestEntity>()
        );

        return new PageUtils(page);
    }

    @Resource
    private MemberService memberService;

    @Resource(name = "RedisTemplate")
    private RedisTemplate redisTemplate;

    @Resource
    private TokenService tokenService;


    /**
     * 创建关注信息
     * @param memberId
     * @param beingMemberId
     * @return
     */
    @Override
    public RespBean createInterest(Long memberId, Long beingMemberId) {
        if ( memberId.equals(beingMemberId) ){
            throw new RRException("您不能关注自己哦");
        }
        MemberEntity member = memberService.getOne(new QueryWrapper<MemberEntity>().eq("id", beingMemberId));
        check(memberId, beingMemberId, member, true);
        MemberInterestEntity interest = this.getOne(new QueryWrapper<MemberInterestEntity>().eq("member_id", memberId)
                .eq("being_member_id", beingMemberId));
        if ( interest == null ){
            interest = new MemberInterestEntity();
            Date date = new Date();
            interest.setCreateTime(date);
            interest.setStatus(1);
            interest.setBeingMemberId(beingMemberId);
            interest.setMemberId(memberId);
            baseMapper.insert(interest);
        }else if( interest != null){
            // 更新
            interest.setStatus(1);
            interest.setCreateTime(new Date());
            this.updateById(interest);
        }

        return RespBean.success("您对" + member.getNickname() + "进行了关注");
    }


    /**
     * 删除关注信息
     * @param memberId
     * @param beingMemberId
     * @return
     */
    @Override
    public RespBean deleteInterest(Long memberId, Long beingMemberId) {
        if ( memberId.equals(beingMemberId) ){
            throw new RRException("用户信息异常,请联系管理员");
        }
        MemberEntity member = memberService.getOne(new QueryWrapper<MemberEntity>().eq("id", beingMemberId));
        String nickname = member.getNickname();

        // 校验
        check(memberId, beingMemberId, member, false);

        MemberInterestEntity interest = this.getOne(new QueryWrapper<MemberInterestEntity>().eq("member_id", memberId)
                .eq("being_member_id", beingMemberId));
        if ( interest != null ){
            interest.setStatus(0);
            this.updateById(interest);
            return RespBean.success("取消关注" + nickname + "成功");
        }
        if ( member != null ){
            nickname = member.getNickname();
        }
        return RespBean.error("取消关注" + nickname + "失败");
    }


    /**
     * 获取用户关注的所有用户
     * @param memberId
     * @return
     */
    @Override
    public RespBean getInterest(Long memberId) {
        List<MemberInterestEntity> list = this.list(new QueryWrapper<MemberInterestEntity>().eq("member_id", memberId)
                .eq("status", 1));

        List< InterestVo> respList = new ArrayList<>();
        InterestVo interestVo = null;
        if ( list == null && list.size() <= 0 ){
            throw new RRException("当前登录用户信息异常");
        }
        else if ( list.size() > 0) {
            for (MemberInterestEntity interestEntity : list) {
                MemberEntity member = memberService.getOne(new QueryWrapper<MemberEntity>().eq("id", interestEntity.getBeingMemberId())
                        .eq("status", 1));
                interestVo = null;
                if ( member != null ){
                    interestVo = new InterestVo();
                    TokenEntity token = tokenService.getOne(new QueryWrapper<TokenEntity>().eq("member_id", member.getId()));
                    Object RMember = redisTemplate.opsForValue().get("member:" + token);
                    TokenEntity tokenEntity = tokenService.checkTokenTime(token.getToken(), null);
                    Date lastLoginTime = token.getExpireTime();

                    interestVo.setOnline((RMember!=null&&tokenEntity!=null)?true:false);
                    interestVo.setHeader(member.getHeader());
                    interestVo.setNickname(member.getNickname());
                    interestVo.setMemberId(member.getId());
                    interestVo.setLastLoginTime(lastLoginTime);
                }
                respList.add(interestVo);
            }
        }
        if ( respList.size() == 0 ){
            respList = null;
        }
        return RespBean.success("获取成功").put("data", respList);
    }


    /**
     * 校验是否合法
     * @param memberId
     * @param beingMemberId
     */
    public void check(Long memberId, Long beingMemberId, MemberEntity member, Boolean is){
        if ( memberId == null || memberId == 0){
            throw new RRException("用户未登录", 402);
        }
        if ( beingMemberId == null || beingMemberId == 0){
            throw new RRException("被关注用户不存在");
        }

        if ( is ){
            // 被关注用户不存在
            if ( member == null ){
                throw new RRException("被关注用户不存在");
            }
            if ( member != null && member.getStatus().equals(0) ){
                throw new RRException("被关注用户不存在");
            }
        }

    }
}
